package com.base.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自动化生产类
 * 
 * @author Administrator
 *
 */
public class Produce {
	/**
	 * java生成UUID类
	 * 
	 * @return
	 */
	public static String getUUID() {
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		String uuidStr = str.replace("-", "");
		return uuidStr;
	}

	/**
	 * 获取现在时间
	 *
	 * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
	 */
	public static Date getNowDate() {
		Calendar c = Calendar.getInstance();
		Date nowTime = c.getTime();
		return nowTime;
	}

	/**
	 * 指定日期加上天数后的日期
	 * 
	 * @param num
	 *            为增加的天数
	 * @param newDate
	 *            创建时间
	 * @return
	 * @throws ParseException
	 */
	public static Date plusDay(int num, Date oldDate) {
		Date currdate = oldDate;
		//TODO
//		System.out.println("推迟的天数是：" + num);
//		System.out.println("现在的日期是：" + currdate);
		Calendar ca = Calendar.getInstance();
		// TODO 存入指定的日期 否则 获取系统时间
		ca.setTime(currdate);
		ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
		currdate = ca.getTime();
		return currdate;
	}

	public static String parmsToString(Object... objects) {
		String str = ">>>";
		for (Object o : objects) {
			if (o != null) {
				str += o.toString() + ",";
			}
		}
		return str;
	}
	/**
	 *  @Date: 2020/5/30 10:04
	 *  @Description:
	 *  判断是否为数字
	 */ 
	public static boolean isNumeric(String str){
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * date2比date1多的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int differentDays(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		int day1 = cal1.get(Calendar.DAY_OF_YEAR);
		int day2 = cal2.get(Calendar.DAY_OF_YEAR);
		int year1 = cal1.get(Calendar.YEAR);
		int year2 = cal2.get(Calendar.YEAR);
		if (year1 != year2) {
			//同一年
			int timeDistance = 0;
			for (int i = year1; i < year2; i++) {
				if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
					//闰年
					timeDistance += 366;
				} else {
					//不是闰年
					timeDistance += 365;
				}
			}
			return timeDistance + (day2 - day1);
		} else {
			//不同年
			System.out.println("判断day2 - day1 : " + (day2 - day1));
			return day2 - day1;
		}
    }

	public static boolean areSameDay(Date dateA, Date dateB) {
		Calendar calDateA = Calendar.getInstance();
		calDateA.setTime(dateA);

		Calendar calDateB = Calendar.getInstance();
		calDateB.setTime(dateB);
		return calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)
				&& calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)
				&& calDateA.get(Calendar.DAY_OF_MONTH) == calDateB.get(Calendar.DAY_OF_MONTH);
	}

	public static void main(String[] args) {
		System.out.println(areSameDay(getNowDate(), plusDay(0, getNowDate())));
	}
	
	//判断日期格式
	public static boolean isValidDate(String str) {
	      boolean convertSuccess=true;
           // 指定日期格式为四位年-两位月份-两位日期，注意yyyy-MM-dd区分大小写；
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	       try {
              // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007-02-29会被接受，并转换成2007-03-01
	          format.setLenient(false);
	          format.parse(str);
	       } catch (ParseException e) {
	          // e.printStackTrace();
	          // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
	          convertSuccess=false;
	       } 
	       return convertSuccess;
	}
	
	  /**
     * 根据毫秒时间戳来格式化字符串
     * 今天显示今天、昨天显示昨天、前天显示前天.
     * 早于前天的显示具体年-月-日，如2017-06-12；
     * @param timeStamp 毫秒值
     * @return 今天 昨天 前天 或者 yyyy-MM-dd HH:mm:ss类型字符串
     */
    public static String format(long timeStamp) {
        long curTimeMillis = System.currentTimeMillis();
        Date curDate = new Date(curTimeMillis);
        int todayHoursSeconds = curDate.getHours() * 60 * 60;
        int todayMinutesSeconds = curDate.getMinutes() * 60;
        int todaySeconds = curDate.getSeconds();
        int todayMillis = (todayHoursSeconds + todayMinutesSeconds + todaySeconds) * 1000;
        long todayStartMillis = curTimeMillis - todayMillis;
                if(timeStamp >= todayStartMillis) {
                    return "今天";
            }
        int oneDayMillis = 24 * 60 * 60 * 1000;
        long yesterdayStartMilis = todayStartMillis - oneDayMillis;
                if(timeStamp >= yesterdayStartMilis) {
                    return "昨天";
            }
        long yesterdayBeforeStartMilis = yesterdayStartMilis - oneDayMillis;
                if(timeStamp >= yesterdayBeforeStartMilis) {
                    return "前天";
            }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(new Date(timeStamp));
    }
    
    /**
	 * 格式化时间（输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间）
	 *
	 * @param time
	 *            需要格式化的时间 如"2014-07-14 19:01:45"
	 * @param pattern
	 *            输入参数time的时间格式 如:"yyyy-MM-dd HH:mm:ss"
	 *            <p/>
	 *            如果为空则默认使用"yyyy-MM-dd HH:mm:ss"格式
	 * @return time为null，或者时间格式不匹配，输出空字符""
	 */
	public static String formatDisplayTime(String time, String pattern) {
		String display = "";
		int tMin = 60 * 1000;
		int tHour = 60 * tMin;
		int tDay = 24 * tHour;
 
		if (time != null) {
			if (pattern == null)
				pattern = "yyyy-MM-dd HH:mm:ss";
			try {
				Date tDate = new SimpleDateFormat(pattern).parse(time);
				Date today = new Date();
				SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
				SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
				Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
				Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
				Date beforeYes = new Date(yesterday.getTime() - tDay);
				if (tDate != null) {
					@SuppressWarnings("unused")
					SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
					long dTime = today.getTime() - tDate.getTime();
					if (tDate.before(thisYear)) {
						display = new SimpleDateFormat("yyyy年MM月dd日").format(tDate);
					} else {
 
						if (dTime < tMin) {
							display = "刚刚";
						} else if (dTime < tHour) {
							display = (int) Math.ceil(dTime / tMin) + "分钟前";
						} else if (dTime < tDay && tDate.after(yesterday)) {
							display = (int) Math.ceil(dTime / tHour) + "小时前";
						} else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
							display = "昨天  " + new SimpleDateFormat("HH:mm").format(tDate);
						} else {
//							display = multiSendTimeToStr(tDate.getTime() / 1000);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
 
		return display;
	}
	
	
	public static int getDistanceTime(Date endDate, Date nowDate) {
	    long nh = 1000 * 60 * 60;
	    // long ns = 1000;
	    // 获得两个时间的毫秒时间差异
	    long diff = nowDate.getTime() - endDate.getTime();
	    // 计算差多少小时
	    long hour = diff / nh;
	    return Integer.parseInt(String.valueOf(hour));
	}

	/**
	 * 判断时间是否在时间段内
	 * @param nowTime
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);
		Calendar begin = Calendar.getInstance();
		begin.setTime(beginTime);
		Calendar end = Calendar.getInstance();
		end.setTime(endTime);

		return date.after(begin) && date.before(end);
	}

	/**
	 * 是否是手机号码
	 *
	 * @param mobile 手机号码
	 *
	 *
	 * @return true/false
	 */
	public static Boolean isMobile(String mobile) {
//		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Pattern p = Pattern.compile("^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$");
		Matcher m = p.matcher(mobile);
		return m.matches();
	}

	/**
	 * 是否是苹果手机
	 *
	 * @param request 请求对象
	 *
	 *
	 * @return true/false
	 */
	public static Boolean isApple(HttpServletRequest request) {
		String agent= request.getHeader("user-agent");
        return agent.contains("iPhone") || agent.contains("iPod") || agent.contains("iPad");
    }

	/**
	 * 日期添加到分钟得到新时间(用于计算考试时间段)
	 * @param day 开始时间
	 * @param x		相隔分钟数（如开考的时间）
	 * @return
	 */
	public static String addDateMinut(String day, int x) {
		//入参的格式
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
		Date date = null;
		try {
			date = format.parse(day);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		if (date == null)
			return "";
		System.out.println("front:" + format.format(date));
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, x);// 24小时制
		//得到结算后的结果 yyyy-MM-dd HH:mm
		date = cal.getTime();
		System.out.println("after:" + format.format(date));
		cal = null;
		//转换结果的格式 HH:mm
		return format.format(date);
	}

	/**
	 * 随机生成汉字
	 * @return
	 */
	public static String createWord() {
		String str = null;
		int hs, ls;
		Random random = new Random();
		hs = (176 + Math.abs(random.nextInt(39)));
		ls = (161 + Math.abs(random.nextInt(93)));
		byte[] b = new byte[2];
		b[0] = (new Integer(hs).byteValue());
		b[1] = (new Integer(ls).byteValue());
		try {
			str = new String(b, "GBK"); //转成中文
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return str;
	}
}
